<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/5/13 16:52
 */

namespace App\Logic\Goods;

use App\Exceptions\RJsonError;
use App\Logic\CommLogic;
use App\Models\Material\Material;
use App\Services\PddInterface;
use Cache;
use OSS\Core\OssException;
use OSS\OssClient;

class TransformLogic extends CommLogic
{

    // 默认推广位
    public $pid = '9569620_187098373';

    /**
     * 商品列表
     *
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return void
     */
    public function lists($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $params = array(
            'pid' => $this->pid,
            'keyword' => $where['keyword'],
            'page' => $pageData['pageNow'],
            'page_size' => $pageData['pageSize'],
        );
        $requestId = 'pdd.ddk.goods.search';
        $response = PddInterface::getInstance($params)->request($requestId);
        $data = $response['goods_search_response'];
        return data($data['goods_list']);
    }

    /**
     * 商品详情
     *
     * @param [type] $params
     * @return void
     */
    public function transform($params)
    {
        try {
            $params = array(
                'pid' => $this->pid,
                'goods_img_type' => 2,
                'need_sku_info' => true,
                'goods_sign' => $params['goods_sign']
            );
            $requestId = 'pdd.ddk.goods.detail';
            $detail = PddInterface::getInstance($params)->request($requestId);
            $response = $detail['goods_detail_response']['goods_details'][0];
            return data($response);
            $goods_cover = $this->imageToOss($response['goods_image_url']);
            $goods_thumb = '<p>';
            $md_content = '';
            foreach($response['goods_gallery_urls'] as $item){
                $data = $this->imageToOss($item);
                $goods_thumb .= "<img src='".$data['url']."' alt='".$data['name']."' />";
                $md_content .= "![" .$data['name']. "](".$data['url'].")";
            }
            $goods_thumb .= '</p>';

            $video_urls = [];
            if ($response['video_urls']) {
                $video_urls = $this->imageToOss($response['video_urls']);
            }
            
            // 开启转存
            $data = array(
                'goods_name' => $response['goods_name'],
                'goods_price' => sprintf("%.2f", $response['min_group_price'] / 100),
                'line_price' => sprintf("%.2f", $response['min_group_price'] / 100),
                'goods_cover' => json_encode($goods_cover, true),
                'goods_thumb' => json_encode($goods_thumb, true),
                'goods_video' => json_encode($video_urls, true),
                'content' => $goods_thumb,
                'md_content' => $md_content,
            );

            $goods = (new GoodsLogic())->store($data);
            return $goods ? success() : error();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode());
        }
    }

    /**
     * @author ChenGuangHui
     * @dateTime 2022-06-24
     * @param [type] $ma
     */
    private function imageToOss($imgPath)
    {
        $bucket = config('config.aliyun.bucket');
        try {
            $ossClient = new OssClient(config('config.aliyun.access_key'), config('config.aliyun.access_secret'), config('config.aliyun.endpoint'));
            $content = file_get_contents($imgPath);
            $ossClient->putObject($bucket, 'material/tmp/' . last(explode('/',$imgPath)), $content);
            return array(
                'name' => last(explode('/',$imgPath)),
                'url' => 'https://img.easyshop.org.cn/' . trim('material/tmp', '/') . '/' . last(explode('/',$imgPath))
            );
        } catch (OssException $e) {
            throw new RJsonError('阿里云OSS配置错误！');
        }
    }
}